"""
FastAPI应用主入口
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from contextlib import asynccontextmanager

from app.config.database import engine, Base
from app.config.redis import redis_client
from app.utils.scheduled_tasks import ScheduledTasks


# 全局定时任务管理器实例
scheduled_tasks = ScheduledTasks()

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    启动时执行
    """
    # 创建数据库表
    Base.metadata.create_all(bind=engine)
    
    # 测试Redis连接
    try:
        redis_client.ping()
        print("Redis连接成功")
    except Exception as e:
        print(f"Redis连接失败: {e}")
    
    # 启动定时任务
    print("启动定时任务...")
    scheduled_tasks.start_view_count_sync_task()
    print("定时任务启动完成")
    
    yield
    
    # 关闭时执行
    print("应用关闭")
    print("停止定时任务...")
    scheduled_tasks.stop_all_tasks()
    print("定时任务已停止")


# 创建FastAPI应用实例
app = FastAPI(
    title="Python FastAPI Server",
    description="Python FastAPI实现的API服务",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置受信任主机中间件
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"],  # 在生产环境中应该设置具体的主机名
)


# 健康检查端点
@app.get("/health")
async def health_check():
    """
    健康检查接口
    用于监控服务是否正常运行
    """
    return {
        "code": 200,
        "message": "success",
        "data": "服务运行正常"
    }


# 示例接口 - 对应之前添加的hello trae接口
@app.get("/api/hello")
async def hello_trae():
    """
    示例接口
    返回hello trae消息
    """
    return {
        "code": 200,
        "message": "success",
        "data": "hello trae"
    }


# 注册路由
from app.routers import auth, user, video, category, interaction

app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(user.router, prefix="/api/users", tags=["用户"])
app.include_router(video.router, prefix="/api/videos", tags=["视频"])
app.include_router(category.router, prefix="/api/categories", tags=["分类"])
app.include_router(interaction.router, prefix="/api/interactions", tags=["互动"])


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )